<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogTitle"
    :append-to-body="true"
    :close-on-click-modal="true"
    :lock-scroll="false"
    :modal="false"
    modal-class="modal-wrap"
    class="dialog-wrap"
  >
    <el-scrollbar ref="scrollarRef" style="margin-right: -13px; padding-right: 13px">
      <el-form
        :model="formData"
        ref="customerFormRef"
        vloading="formLoading"
        :inline="true"
        label-width="auto"
      >
        <el-form-item label="名称" prop="name">
          <el-text>{{ formData.name }}</el-text>
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-text>{{ formData.shortName }}</el-text>
        </el-form-item>

        <el-form-item label="来源" prop="source">
          <el-text>
            {{
              convertSelectField(
                customerModuleField.immutableFields.get('source')?.options,
                formData.source
              )
            }}
          </el-text>
        </el-form-item>
        <el-form-item label="等级" prop="grade">
          <el-text>
            {{
              convertSelectField(
                customerModuleField.immutableFields.get('grade')?.options,
                formData.grade
              )
            }}
          </el-text>
        </el-form-item>

        <el-form-item label="阶段" prop="stage">
          <el-text>
            {{
              convertSelectField(
                customerModuleField.immutableFields.get('stage')?.options,
                formData.stage
              )
            }}
          </el-text>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-text>
            {{
              convertSelectField(
                customerModuleField.immutableFields.get('state')?.options,
                formData.state
              )
            }}
          </el-text>
        </el-form-item>
        <el-form-item label="拥有人" prop="ownerId">
          <el-text>
            {{ convertSelectFieldName(userList, formData.ownerId, 'username') }}
          </el-text>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-text>
            {{ convertSelectField(deptList, formData.deptId) }}
          </el-text>
        </el-form-item>

        <el-form-item label="国家" prop="countryId">
          <el-text>
            {{ convertSelectField(countryList, formData.countryId) }}
          </el-text>
        </el-form-item>
        <el-form-item label="省" prop="provinceId">
          <el-text>
            {{ convertSelectField(provinceList, formData.provinceId) }}
          </el-text>
        </el-form-item>
        <el-form-item label="市" prop="cityId">
          <el-text>
            {{ convertSelectField(cityList, formData.cityId) }}
          </el-text>
        </el-form-item>
        <el-form-item label="区" prop="districtId">
          <el-text>
            {{ convertSelectField(districtList, formData.districtId) }}
          </el-text>
        </el-form-item>
        <el-form-item label="网址" prop="websites">
          <el-text v-if="formData.websites.length == 0">{{ '' }}</el-text>
          <el-text v-else v-for="row in formData.websites" :key="row.id" class="mr-4">
            {{ row.website }}
          </el-text>
        </el-form-item>

        <el-row>
          <el-form-item label="图片">
            <el-text v-if="imageData.images.length == 0">{{ '' }}</el-text>
            <el-image
              v-else
              style="height: 70px; width: 80px"
              class="mr-2"
              v-for="image in imageData.images"
              :key="image.id"
              :src="image.url"
              :preview-src-list="[image.url!]"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <el-form
        :model="formData"
        ref="customerCustomFormRef"
        vloading="formLoading"
        :inline="true"
        label-width="auto"
      >
        <el-form-item
          v-for="(customerCustomField, index) in customerModuleField.customFields"
          :key="index"
          :label="customerCustomField.showName"
          :prop="customerCustomField.fieldName"
        >
          <el-text v-if="customerCustomField.options.length == 0">{{
            formData[customerCustomField.fieldName]
          }}</el-text>
          <el-text v-else>
            {{
              convertSelectField(
                customerCustomField.options,
                formData[customerCustomField.fieldName]
              )
            }}
          </el-text>
        </el-form-item>
      </el-form>
      <transition-group name="card" tag="div">
        <el-card
          v-for="(contact, index) in formData.contacts"
          :key="cardKey[index]"
          style="margin-bottom: 15px; margin-top: 15px"
          v-show="contact.operateType != 'deleted'"
        >
          <el-collapse v-model="collapses[index]" style="border: none; transition: none">
            <el-collapse-item :name="collapses[index][0]" style="border: none; transition: none">
              <template #title>
                <div style="display: flex">
                  <div class="font-bold">{{ '联系人_' + (index + 1) }}</div>
                  <el-button
                    style="font-weight: bold; margin-left: 15px; margin-top: 12px"
                    :style="contact.isMain ? 'color: green' : 'color:black'"
                    size="small"
                  >
                    {{ contact.isMain ? '主' : '副' }}
                  </el-button>
                </div>
              </template>
              <template #icon="{ isActive }">
                <Icon
                  :size="24"
                  :icon="isActive ? 'ic:round-keyboard-arrow-up' : 'ic:round-keyboard-arrow-down'"
                  class="el-collapse-item-arrow"
                />
              </template>
              <el-form :model="contact" :inline="true" label-width="auto">
                <el-form-item label="姓名" prop="name">
                  <el-text>{{ contact.name }}</el-text>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                  <el-text>{{ contact.nickName }}</el-text>
                </el-form-item>
                <el-form-item label="决策角色" prop="decisionRole">
                  <el-text>
                    {{
                      convertSelectField(
                        contactModuleField.immutableFields.get('decisionRole')?.options,
                        contact.decisionRole
                      )
                    }}
                  </el-text>
                </el-form-item>
                <el-form-item label="职位" prop="position">
                  <el-text>{{ contact.position }}</el-text>
                </el-form-item>
                <el-form-item label="工作状态" prop="workState">
                  <el-text>
                    {{
                      convertSelectField(
                        contactModuleField.immutableFields.get('workState')?.options,
                        contact.workState
                      )
                    }}
                  </el-text>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-text>
                    {{
                      convertSelectField(
                        contactModuleField.immutableFields.get('sex')?.options,
                        contact.sex
                      )
                    }}
                  </el-text>
                </el-form-item>
                <el-row>
                  <el-form-item label="电话" prop="phones">
                    <el-text v-if="contact.phones.length == 0">{{ '' }}</el-text>
                    <el-text v-else v-for="row in contact.phones" :key="row.id" class="mr-4">{{
                      row.phoneNo
                    }}</el-text>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="邮箱" prop="mails">
                    <el-text v-if="contact.mails.length == 0">{{ '' }}</el-text>
                    <el-text v-else v-for="row in contact.mails" :key="row.id" class="mr-4">{{
                      row.mailAddress
                    }}</el-text>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="社交媒体" prop="socialMedias">
                    <el-text v-if="contact.socialMedias.length == 0">{{ '' }}</el-text>
                    <el-text v-else v-for="row in contact.socialMedias" :key="row.id" class="mr-4">
                      {{
                        getIntDictOptions(DICT_TYPE.COMMON_SOCIAL_MEDIA_TYPE).find(
                          (obj) => obj.value == row.socialType
                        )?.label +
                        ':' +
                        row.socialAccount
                      }}
                    </el-text>
                  </el-form-item>
                </el-row>
                <el-form-item label="地址" prop="address">
                  <el-text>{{ contact.address }}</el-text>
                </el-form-item>

                <el-form-item label="名片">
                  <el-text v-if="imageData.contacts[index].length == 0">{{ '' }}</el-text>
                  <el-image
                    v-else
                    style="height: 70px; width: 80px"
                    class="mr-2"
                    v-for="image in imageData.contacts[index]"
                    :key="image.id"
                    :src="image.url"
                    :preview-src-list="[image.url!]"
                  />
                </el-form-item>
              </el-form>
              <el-form :model="contact" vloading="formLoading" :inline="true" label-width="auto">
                <el-form-item
                  v-for="(contactCustomField, customIndex) in contactModuleField.customFields"
                  :key="customIndex"
                  :label="contactCustomField.showName"
                  :prop="contactCustomField.fieldName"
                >
                  <el-text v-if="contactCustomField.options.length == 0">{{
                    contact[contactCustomField.fieldName]
                  }}</el-text>
                  <el-text v-else>
                    {{
                      convertSelectField(
                        contactCustomField.options,
                        contact[contactCustomField.fieldName]
                      )
                    }}
                  </el-text>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </transition-group>
    </el-scrollbar>
  </el-drawer>
</template>
<script setup name="CustomerShow" lang="ts">
import type { UploadUserFile } from 'element-plus'

import { CustomerInfo as CustomerInfoModel } from '@/model/customer/info/CustomerInfo'
import { CustomerImage as CustomerImageModel } from '@/model/customer/info/CustomerImage'
import { CustomerWebsite as CustomerWebsiteModel } from '@/model/customer/info/CustomerWebsite'
import { CustomerContact as CustomerContactModel } from '@/model/customer/contact/CustomerContact'
import { CustomerContactBusinessCard as CustomerContactBusinessCardModel } from '@/model/customer/contact/CustomerContactBusinessCard'
import { CustomerContactMail as CustomerContactMailModel } from '@/model/customer/contact/CustomerContactMail'
import { CustomerContactPhone as CustomerContactPhoneModel } from '@/model/customer/contact/CustomerContactPhone'
import { CustomerContactSocialMedia as CustomerContactSocialMediaModel } from '@/model/customer/contact/CustomerContactSocialMedia'

import * as DeptApi from '@/api/system/dept/dept'
import * as AreaApi from '@/api/infra/data/area'
import * as CustomerApi from '@/api/customer/customer'
import * as UserApi from '@/api/system/user/user'

import { useUserStore } from '@/store/modules/user'
import { SettingBusinessModuleEnum } from '@/utils/constants'
import { cloneDeep } from '@pureadmin/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'

interface imageModel extends UploadUserFile {
  id: number | undefined
}

interface imageDataModel {
  images: imageModel[]
  contacts: imageModel[][]
}

interface CustomerContactMailEditModel extends CustomerContactMailModel {
  operateType: string
}

interface CustomerContactPhoneEditModel extends CustomerContactPhoneModel {
  operateType: string
}

interface CustomerContactSocialMediaEditModel extends CustomerContactSocialMediaModel {
  operateType: string
}

interface CustomerContactEditModel extends CustomerContactModel {
  operateType: string
  businessCards: CustomerContactBusinessCardModel[]
  mails: CustomerContactMailEditModel[]
  phones: CustomerContactPhoneEditModel[]
  socialMedias: CustomerContactSocialMediaEditModel[]
}

interface CustomerWebsiteEditModel extends CustomerWebsiteModel {
  operateType: string
}
interface CustomerInfoEditModel extends CustomerInfoModel {
  images: CustomerImageModel[]
  websites: CustomerWebsiteEditModel[]
  contacts: CustomerContactEditModel[]
}

const userStore = useUserStore()

const emptyContact = {
  id: undefined,
  name: '',
  sex: 0,
  address: '',
  position: '',
  decisionRole: 0,
  workState: 0,
  customField1: '',
  customField2: '',
  customField3: '',
  customField4: '',
  customField5: '',
  customField6: '',
  customField7: '',
  customField8: '',
  customField9: '',
  customField10: '',
  customerId: undefined,
  operateType: 'new',
  businessCards: [],
  mails: [],
  phones: [],
  socialMedias: []
}
const emptyFormData = {
  id: undefined,
  customerNo: '',
  name: '',
  mainImageUrl: '',
  source: 0,
  grade: 0,
  stage: 0,
  state: 0,
  ownerId: userStore.getUser.id,
  countryId: 0,
  provinceId: 0,
  cityId: 0,
  districtId: 0,
  address: '',
  deptId: userStore.getUser.deptId,
  customField1: '',
  customField2: '',
  customField3: '',
  customField4: '',
  customField5: '',
  customField6: '',
  customField7: '',
  customField8: '',
  customField9: '',
  customField10: '',
  customField11: '',
  customField12: '',
  customField13: '',
  customField14: '',
  customField15: '',
  customField16: '',
  customField17: '',
  customField18: '',
  customField19: '',
  customField20: '',
  mainContactId: undefined,
  isRecycle: false,
  images: [],
  websites: [],
  contacts: [{ ...cloneDeep(emptyContact), isMain: true }]
}

const dialogTitle = ref('客户信息')
const dialogVisible = ref(false)
const customerFormRef = ref()
const customerCustomFormRef = ref()

const formData = ref<CustomerInfoEditModel>(cloneDeep(emptyFormData))
const imageData = ref<imageDataModel>({ images: [], contacts: [[]] })

const countryList = ref()
const provinceList = ref()
const cityList = ref()
const districtList = ref()
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const deptList = ref([]) // 树形结构
const scrollarRef = ref()
const collapses = ref([[0]])
const cardCount = ref(1)
const cardKey = ref([0])
const customerModuleField = ref()
const contactModuleField = ref()

/** 打开弹窗 */
const open = async (id) => {
  await reset()
  await dataInit()
  await getCustomerInfo(id)
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const reset = () => {
  formData.value = cloneDeep(emptyFormData)
  collapses.value = [[0]]
  cardCount.value = 1
  cardKey.value = [0]
}

const dataInit = async () => {
  // 加载部门树
  deptList.value = await DeptApi.listAllSimple()
  // 获得用户列表
  userList.value = await UserApi.getOwnerUser()
  // 加载业务字段
  customerModuleField.value = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)

  contactModuleField.value = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER_CONTACT)

  countryList.value = await AreaApi.countryList()

  imageData.value = { images: [], contacts: [[]] }
}

const getCustomerInfo = async (id) => {
  if (id == 0) return

  const customerDetail = await CustomerApi.singleGetDetail(id)

  const count = customerDetail.contacts.length - 1
  for (let index = 0; index < count; index++) {
    cardKey.value.push(cardCount.value)
    collapses.value.push([cardCount.value])
    imageData.value.contacts.push([])
    cardCount.value = cardCount.value + 1
  }
  formData.value = customerDetail
  if (formData.value.provinceId != 0) {
    provinceList.value = await AreaApi.provinceListByCountryId(formData.value.countryId)
  }
  if (formData.value.cityId != 0) {
    cityList.value = await AreaApi.cityListByProvinceId(formData.value.provinceId)
  }
  if (formData.value.districtId != 0) {
    districtList.value = await AreaApi.districtListByCityId(formData.value.cityId)
  }
  initImageData()
}

const initImageData = () => {
  formData.value.images.forEach((image) => {
    imageData.value.images.push({
      id: image.id,
      url: image.url,
      name: image.url
    })
  })
  let contactIndex = 0
  formData.value.contacts.forEach((contact) => {
    contact.businessCards.forEach((card) => {
      imageData.value.contacts[contactIndex].push({
        id: card.id,
        url: card.url,
        name: card.url
      })
    })
    contactIndex++
  })
}

const convertSelectField = (options, id) => {
  if (id == 0 || options == undefined) return ''
  return options.find((obj) => obj.id === id)?.name
}

const convertSelectFieldName = (options, id, name) => {
  if (id == 0 || options == undefined) return ''
  return options.find((obj) => obj.id === id)[name]
}
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  pointer-events: none;
}

:deep(.el-collapse-item__header button) {
  pointer-events: auto;
}

:deep(.el-collapse-item-arrow) {
  pointer-events: auto;
}
:deep(.el-collapse-item__wrap) {
  border: none;
}

:deep(.scroll-wrap) {
  height: 100%;
  margin-right: -17px;
  padding-right: 17px;
}

/* 定义 card 过渡 */
:deep(.card-enter-active) {
  transition: 0.8s ease;
}

:deep(.card-leave-active) {
  transition: 0.8s ease;
}
:deep(.card-entry-to) {
  opacity: 0;
  transform: translateY(30px);
}

:deep(.card-leave-to) {
  opacity: 0;
  transform: translateY(30px);
}

:deep(el-scrollbar) {
  transition: none !important;
}

:deep(.modal-wrap) {
  pointer-events: none !important;
}
:deep(.dialog-wrap) {
  pointer-events: auto !important;
}
:deep(.el-text) {
  border-bottom: 1px solid #e5e7e9;
  width: 240px;
  text-align: center;
  min-height: 32px;
}
</style>
